package chpt09;

public class ThreadStopTest {

	public static void main(String[] args) throws Exception {
		System.out.println("我是主线程");
		SenderThread taskSend = new SenderThread();
		ReciverThread recvTask = new ReciverThread();

		Thread sendThread = new Thread(taskSend);
		Thread recvThread = new Thread(recvTask);
		sendThread.start();// 启动send线程
		recvThread.start();// 启动recv线程

		for (int i = 0; i < 5; i++) {
			System.out.println("主线程正在运行!");
			Thread.sleep(1000);
		}

		System.out.println("主线程结束!!!");
		taskSend.stopMe();
		recvTask.stopMe();
	}

}

class SenderThread implements Runnable {

	private volatile boolean stop = false;

	public void stopMe() {
		stop = true;
	}

	@Override
	public void run() {
		System.out.println("发送消息线程开始运行");
		while (!stop) {
			System.out.println("发送消息");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// 如果在线程sleep时收到中断，也视为停止信号
	            System.out.println("发送线程被中断唤醒");
	            break; // 退出循环
			}
		}
		System.out.println("发送消息线程结束！！！");
	}

}

class ReciverThread implements Runnable {

	private boolean stop = false;

	public void stopMe() {
		stop = true;
	}

	@Override
	public void run() {
		System.out.println("接受消息线程开始运行");
		while (!stop) {
			System.out.println("接受消息");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("接收线程被中断唤醒");
	            break; // 退出循环
			}
		}
		System.out.println("接收消息线程结束！！！");
	}

}
